﻿using System;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Drawing;
using Crystal.CLL;
using Crystal.CustomControls;
using Crystal.CustomControls.Controls;
using Infragistics.Win.UltraWinEditors;
using Infragistics.Win.Misc;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace Crystal.CLL
{
    public class BaseForm : Form
    {
        #region Constructor

        public BaseForm()
        {
            Stream imgStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Crystal.CLL.Images.Bullet.ico");
            this.Icon = new Icon(imgStream);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            Load += BaseForm_Load;
        }

        private void BaseForm_Load(object sender, System.EventArgs e)
        {
            int[] Values = new int[3];
            if (CommonCustomControls.IsValidString(StyleManager.GetStyle("FormBackColor"), ref Values))
            {
                this.BackColor = System.Drawing.Color.FromArgb(Values[0], Values[1], Values[2]);
            }
        }

        //protected override void OnLoad(EventArgs e)
        //{
        //    //this.FindForm().Text = PageTitle.GetTitle(GetUsablePagePath());

        //    int[] Values = new int[3];
        //    if (Crystal.CustomControls.CommonCustomControls.IsValidString(StyleManager.GetStyle("FormBackColor"), ref Values))
        //    {
        //        this.BackColor= System.Drawing.Color.FromArgb(Values[0], Values[1], Values[2]);
        //    }
        //}

        #endregion

        #region Logging
        /// <summary>
        /// Log the error
        /// </summary>
        public void LogErrorToDatabase(Exception ex)
        {
            LoggingManager.WriteLog(CommonCLL.UserName, ex.ToString(), "Form - " + this.FindForm().Name + Environment.NewLine);
            //throw ex;
        }

        public void LogErrorToDatabase(string message)
        {
            LoggingManager.WriteLog(CommonCLL.UserName, message, "Form - " + this.FindForm().Name + Environment.NewLine);
            //throw ex;
        }

        public void FormulateAndLogError(Exception ex, string pstrScreenName, int pintProjectID)
        {
            MessageBox.Show(ex.ToString());
            //MessageBox.Show(ex.Message);
            System.Text.StringBuilder Logmessage = new System.Text.StringBuilder();
            StackTrace stackTrace = new StackTrace();
            if (pintProjectID > 0)
            {
                Logmessage.Append("Project ID - ");
                Logmessage.Append(Convert.ToString(pintProjectID));
                Logmessage.Append(Environment.NewLine);
            }
            Logmessage.Append("There is an error in " + stackTrace.GetFrame(1).GetMethod().Name + " of " + pstrScreenName + ".");
            Logmessage.Append(Environment.NewLine);
            Logmessage.Append("Error Message - ");
            Logmessage.Append(ex.ToString());
            LogErrorToDatabase(Logmessage.ToString());
        }
        #endregion

        #region Controls
        /// <summary>
        /// Clear Controls 
        /// </summary>
        /// <param name="ctrlCol"></param>
        public void ClearControls(ControlCollection ctrlCol)
        {
            foreach (Control ctrl in ctrlCol)
            {
                if (ctrl.Visible)
                {
                    if (ctrl.HasChildren)
                    {
                        //ControlCollection lcs = ctrl.Controls;
                        //ClearControls(ctrl.get);
                    }
                    else if (ctrl.GetType().Equals(typeof(TextBox)))
                    {
                        ((TextBox)ctrl).Text = string.Empty;
                    }
                    else if (ctrl.GetType().Equals(typeof(ComboBox)))
                    {
                        ((ComboBox)ctrl).SelectedIndex = 0;
                    }
                    else if (ctrl.GetType().Equals(typeof(CheckBox)))
                    {
                        ((CheckBox)ctrl).Checked = false;
                    }
                }
            }
        }

        /// <summary>
        /// Disable Controls 
        /// </summary>
        /// <param name="ctrlCol"></param>
        public void DisableControls(ControlCollection ctrlCol, string[] lstrExcluding)
        {

            foreach (Control ctrl in ctrlCol)
            {
                if (lstrExcluding == null)
                {
                    if (ctrl.GetType().Equals(typeof(LinkLabel)) == true)
                        ctrl.Enabled = false;
                }
                else
                    if (((IList<string>)lstrExcluding).Contains(ctrl.Name) == false)
                    {
                        ctrl.Enabled = false;
                    }
            }
        }

        #endregion

        #region "Message Box Methods"

        /// <summary>
        /// Showing all the other message than querystring.
        /// </summary>
        /// <param name="args"></param>
        protected void ShowMessageBox(DBResult oResult, params object[] args)
        {
            MessageBox.Show(MessageManager.GetMessage(oResult.ToString(), args), MessageManager.GetMessage("CRYSTAL"));
        }

        protected string ShowErrorMessage(DBResult oResult, params object[] args)
        {
            return
                MessageManager.GetMessage(oResult.ToString(), args);
        }


        public string GetUsablePagePath()
        {
            string pageTitle = this.FindForm().Name;
            return pageTitle;
        }

        #endregion

        #region Validations

        protected string RemoveSpecialChar(TextBox txt)
        {
            return txt.Text.Trim().Replace("'", "''").Replace("_", "[_]").Replace("%", "[%]");
        }

        #endregion

        #region Controls
        /// <summary>
        /// Clear Controls 
        /// </summary>
        /// <param name="ctrlCol"></param>
        /// 
        public void RangeValidator(Control ctrl, string MaxValue, string MinValue, string Message)
        {
            if (ctrl.GetType().Equals(typeof(CrystalTextEditor)))
            {
                ValidationManager.RangeValidator rangeValidator = new ValidationManager.RangeValidator();
                rangeValidator.ControlToValidate = ((TextBox)ctrl);
                rangeValidator.MaximumValue = MaxValue;
                rangeValidator.MinimumValue = MinValue;
                if (MinValue.ToString().Contains("."))
                    rangeValidator.Type = ValidationManager.ValidationDataType.Double;
                else
                    rangeValidator.Type = ValidationManager.ValidationDataType.Int64;
                object[] parms = { MaxValue, Message };
                rangeValidator.ErrorMessage = ShowErrorMessage(DBResult.VALUEEXCEED, parms);
            }
            else if (ctrl.GetType().Equals(typeof(UltraTextEditor)))
            {
                ValidationManager.RangeValidator rangeValidator = new ValidationManager.RangeValidator();
                rangeValidator.ControlToValidate = ((UltraTextEditor)ctrl);
                rangeValidator.MaximumValue = MaxValue;
                rangeValidator.MinimumValue = MinValue;
                if (MinValue.ToString().Contains("."))
                    rangeValidator.Type = ValidationManager.ValidationDataType.Double;
                else
                    rangeValidator.Type = ValidationManager.ValidationDataType.Int64;
                object[] parms = { MaxValue, Message };
                rangeValidator.ErrorMessage = ShowErrorMessage(DBResult.VALUEEXCEED, parms);

            }
        }

        public void ApplyRegexValidation(Control ctrl, ValidationManager.RegexType type, string Message)
        {
            if (ctrl.GetType().Equals(typeof(CrystalTextEditor)))
            {
                ValidationManager.RegularExpressionValidator regex = new ValidationManager.RegularExpressionValidator();
                regex.ControlToValidate = ((TextBox)ctrl);
                regex.IsRequired = false;
                regex.ValidationExpression = ValidationManager.regexString(type);

                if (ValidationManager.RegexType.Decimal == type)
                    regex.ErrorMessage = ShowErrorMessage(DBResult.DECIMAL_VALIDATION, BaseClass.Capitalize(Message));
                else if (ValidationManager.RegexType.Double == type)
                    regex.ErrorMessage = ShowErrorMessage(DBResult.DOUBLE_VALIDATION , BaseClass.Capitalize(Message));
                else
                    regex.ErrorMessage = ShowErrorMessage(DBResult.INVALID, BaseClass.Capitalize(Message));

            }
            else if (ctrl.GetType().Equals(typeof(UltraTextEditor)))
            {
                ValidationManager.RegularExpressionValidator regex = new ValidationManager.RegularExpressionValidator();
                regex.ControlToValidate = ((UltraTextEditor)ctrl);
                regex.IsRequired = false;
                regex.ValidationExpression = ValidationManager.regexString(type);

                if (ValidationManager.RegexType.Decimal == type)
                    regex.ErrorMessage = ShowErrorMessage(DBResult.DECIMAL_VALIDATION, BaseClass.Capitalize(Message));
                if (ValidationManager.RegexType.Double  == type)
                    regex.ErrorMessage = ShowErrorMessage(DBResult.DOUBLE_VALIDATION , BaseClass.Capitalize(Message));
                else
                    regex.ErrorMessage = ShowErrorMessage(DBResult.INVALID, BaseClass.Capitalize(Message));

            }
        }
        public void DisableRightClickInfTextEditor(Control ctrl)
        {

            if (ctrl.GetType().Equals(typeof(CrystalTextEditor)))
            {
                ctrl.ContextMenu = new ContextMenu();
            }

        }
        public void ValidateControls(Control.ControlCollection ctrlCol, bool isforDropDown)
        {
            foreach (Control ctrl in ctrlCol)
            {
                if (ctrl.GetType().Equals(typeof(TextBox)))
                {
                    string ctrlName = ValidationMessageManager.GetMessage(ctrl.Name.ToString());
                    if (!string.IsNullOrEmpty(ctrlName))
                    {
                        ValidationManager.RequiredFieldValidator reqValidation = new ValidationManager.RequiredFieldValidator();
                        reqValidation.ControlToValidate = ((TextBox)ctrl);
                        reqValidation.ErrorMessage = ShowErrorMessage(DBResult.REQUIRED, BaseClass.Capitalize(ctrlName));
                    }
                }
                else if (ctrl.GetType().Equals(typeof(CrystalTextEditor)))
                {
                    string ctrlName = ValidationMessageManager.GetMessage(ctrl.Name.ToString());
                    if (!string.IsNullOrEmpty(ctrlName))
                    {
                        ValidationManager.RequiredFieldValidator reqValidation = new ValidationManager.RequiredFieldValidator();
                        reqValidation.ControlToValidate = ((CrystalTextEditor)ctrl);
                        reqValidation.ErrorMessage = ShowErrorMessage(DBResult.REQUIRED, BaseClass.Capitalize(ctrlName));
                    }
                }

                else if (isforDropDown)
                {
                    if (ctrl.GetType().Equals(typeof(ComboBox)))
                    {
                        string ctrlName = ValidationMessageManager.GetMessage(ctrl.Name.ToString());
                        if (!string.IsNullOrEmpty(ctrlName))
                        {
                            ValidationManager.RequiredFieldValidator reqValidation = new ValidationManager.RequiredFieldValidator();
                            reqValidation.ControlToValidate = ((ComboBox)ctrl);
                            reqValidation.ErrorMessage = ShowErrorMessage(DBResult.SELECTONE, BaseClass.Capitalize(ctrlName));
                        }
                    }
                    else if (ctrl.GetType().Equals(typeof(ComboToolTip)))
                    {
                        string ctrlName = ValidationMessageManager.GetMessage(ctrl.Name.ToString());
                        if (!string.IsNullOrEmpty(ctrlName))
                        {
                            ValidationManager.RequiredFieldValidator reqValidation = new ValidationManager.RequiredFieldValidator();
                            reqValidation.ControlToValidate = ((ComboToolTip)ctrl);
                            reqValidation.ErrorMessage = ShowErrorMessage(DBResult.SELECTONE, BaseClass.Capitalize(ctrlName));
                        }
                    }
                    else if (ctrl.GetType().Equals(typeof(UltraComboEditor)))
                    {
                        string ctrlName = ValidationMessageManager.GetMessage(ctrl.Name.ToString());
                        if (!string.IsNullOrEmpty(ctrlName))
                        {
                            ValidationManager.RequiredFieldValidator reqValidation = new ValidationManager.RequiredFieldValidator();
                            reqValidation.ControlToValidate = ((UltraComboEditor)ctrl);
                            reqValidation.ErrorMessage = ShowErrorMessage(DBResult.SELECTONE, BaseClass.Capitalize(ctrlName));
                        }
                    }
                    else if (ctrl.GetType().Equals(typeof(UltraTextEditor)))
                    {
                        string ctrlName = ValidationMessageManager.GetMessage(ctrl.Name.ToString());
                        if (!string.IsNullOrEmpty(ctrlName))
                        {
                            ValidationManager.RequiredFieldValidator reqValidation = new ValidationManager.RequiredFieldValidator();
                            reqValidation.ControlToValidate = ((UltraTextEditor)ctrl);
                            reqValidation.ErrorMessage = ShowErrorMessage(DBResult.SELECTONE, BaseClass.Capitalize(ctrlName));
                        }
                    }
                }

            }
        }
        public void RequiredDateTimeControl(Control ctrl, string controlText,bool isRequired = true )
        {
            if (ctrl.GetType().Equals(typeof(Infragistics.Win.UltraWinEditors.UltraDateTimeEditor)))
                if (!string.IsNullOrEmpty(controlText))
                {
                    ValidationManager.RequiredFieldValidator reqValidation = new ValidationManager.RequiredFieldValidator();
                    reqValidation.IsRequired = isRequired ;
                    reqValidation.ControlToValidate = ((Infragistics.Win.UltraWinEditors.UltraDateTimeEditor)ctrl);
                    reqValidation.ErrorMessage = ShowErrorMessage(DBResult.REQUIRED, BaseClass.Capitalize(controlText));
                }
        }
        public void RequiredValidateControl(Control ctrl, string controlText)
        {
            if (ctrl.GetType().Equals(typeof(ComboBox)))
            {
                if (!string.IsNullOrEmpty(controlText))
                {
                    ValidationManager.RequiredFieldValidator reqValidation = new ValidationManager.RequiredFieldValidator();
                    reqValidation.ControlToValidate = ((ComboBox)ctrl);
                    reqValidation.ErrorMessage = ShowErrorMessage(DBResult.SELECTONE, BaseClass.Capitalize(controlText));
                }
            }
            else if (ctrl.GetType().Equals(typeof(ComboToolTip)))
            {
                if (!string.IsNullOrEmpty(controlText))
                {
                    ValidationManager.RequiredFieldValidator reqValidation = new ValidationManager.RequiredFieldValidator();
                    reqValidation.ControlToValidate = ((ComboToolTip)ctrl);
                    reqValidation.ErrorMessage = ShowErrorMessage(DBResult.SELECTONE, BaseClass.Capitalize(controlText));
                }
            }
            else if (ctrl.GetType().Equals(typeof(CrystalTextEditor)))
            {
                //string ctrlName = ValidationMessageManager.GetMessage(ctrl.Name.ToString());
                if (!string.IsNullOrEmpty(controlText))
                {
                    ValidationManager.RequiredFieldValidator reqValidation = new ValidationManager.RequiredFieldValidator();
                    reqValidation.ControlToValidate = ((CrystalTextEditor)ctrl);
                    reqValidation.ErrorMessage = ShowErrorMessage(DBResult.REQUIRED, BaseClass.Capitalize(controlText));
                }
            }
            else if (ctrl.GetType().Equals(typeof(UltraComboEditor)))
            {
                if (!string.IsNullOrEmpty(controlText))
                {
                    ValidationManager.RequiredFieldValidator reqValidation = new ValidationManager.RequiredFieldValidator();
                    reqValidation.ControlToValidate = ((UltraComboEditor)ctrl);
                    reqValidation.ErrorMessage = ShowErrorMessage(DBResult.SELECTONE, BaseClass.Capitalize(controlText));
                }
            }
            else if (ctrl.GetType().Equals(typeof(UltraTextEditor)))
            {
                //string ctrlName = ValidationMessageManager.GetMessage(ctrl.Name.ToString());
                if (!string.IsNullOrEmpty(controlText))
                {
                    ValidationManager.RequiredFieldValidator reqValidation = new ValidationManager.RequiredFieldValidator();
                    reqValidation.ControlToValidate = ((UltraTextEditor)ctrl);
                    reqValidation.ErrorMessage = ShowErrorMessage(DBResult.REQUIRED, BaseClass.Capitalize(controlText));
                }
            }
        }

        public void ButtonDisable(Control.ControlCollection ctrlCol, bool istrue)
        {
            foreach (Control ctrl in ctrlCol)
            {
                if (ctrl.GetType().Equals(typeof(UltraButton)))
                {
                    if (istrue)
                        ctrl.BackColor = Color.FromArgb(29, 79, 189);
                    else
                        ctrl.BackColor = Color.FromArgb(19, 40, 67);

                }
            }
        }

        public void RemoveRequiredValidation(Control ctrl, string controlText)
        {
            if (ctrl.GetType().Equals(typeof(ComboBox)))
            {
                if (!string.IsNullOrEmpty(controlText))
                {
                    ValidationManager.RequiredFieldValidator reqValidation = new ValidationManager.RequiredFieldValidator();
                    reqValidation.IsRequired = false;
                    reqValidation.ControlToValidate = ((ComboBox)ctrl);
                    reqValidation.ErrorMessage = ShowErrorMessage(DBResult.SELECTONE, BaseClass.Capitalize(controlText));
                }
                else if (ctrl.GetType().Equals(typeof(ComboToolTip)))
                {
                    if (!string.IsNullOrEmpty(controlText))
                    {
                        ValidationManager.RequiredFieldValidator reqValidation = new ValidationManager.RequiredFieldValidator();
                        reqValidation.IsRequired = false;
                        reqValidation.ControlToValidate = ((ComboToolTip)ctrl);
                        reqValidation.ErrorMessage = ShowErrorMessage(DBResult.SELECTONE, BaseClass.Capitalize(controlText));

                    }
                }
            }
        }

        #endregion

        public void CreateErrorLog(System.Text.StringBuilder Message)
        {
            LogEntry Log = null;
            try
            {
                Log = new LogEntry();
                Message.Append(Environment.NewLine);
                Message.Append("Local Machine Date/Time - ");
                Message.Append(DateTime.Now.Day.ToString());
                Message.Append("/");
                Message.Append(DateTime.Now.Date.Month.ToString());
                Message.Append("/");
                Message.Append(DateTime.Now.Date.Year.ToString());
                Message.Append("  (DD-MM-YYYY)  ");
                Message.Append(DateTime.Now.Hour.ToString());
                Message.Append(":");
                Message.Append(DateTime.Now.Minute.ToString());
                Message.Append(":");
                Message.Append(DateTime.Now.Second.ToString());
                Message.Append(Environment.NewLine);
                Log.Message = Message.ToString();
                Logger.Write(Log);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Log = null;
                Message = null;
            }
        }
        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // BaseForm
            // 
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.Name = "BaseForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.ResumeLayout(false);

        }

        #region "Focus on instance"
        public void FocusOnExistingInstance(string FormText, string Filename, FormWindowState windowstate, ref bool isAlreadyOpen)
        {
            Form objAdd = null;
            try
            {
                for (int i = 0; i <= Application.OpenForms.Count - 1; i++)
                {
                    if ((Application.OpenForms[i].Name == Filename))
                    {
                        objAdd = Application.OpenForms[i];
                        if ((objAdd.Text == FormText))
                        {
                            if ((windowstate == FormWindowState.Maximized))
                            {
                                objAdd.WindowState = FormWindowState.Maximized;
                            }
                            if ((windowstate == FormWindowState.Normal))
                            {
                                objAdd.WindowState = FormWindowState.Normal;
                            }
                            isAlreadyOpen = true;
                            objAdd.Focus();
                        }
                        break;

                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                //'Logging
                System.Text.StringBuilder MsgLog = new System.Text.StringBuilder();
                MsgLog.Append("There is error in FocusTheExistingInstanceOfForm in Client Management.");
                MsgLog.Append(Environment.NewLine);
                MsgLog.Append("Error Details:- ");
                MsgLog.Append(ex.ToString());
                CreateErrorLog(MsgLog);
                MsgLog = null;
            }
            finally
            {
                objAdd = null;
            }

        }

        #endregion

    }
}
